﻿using COSXML;
using COSXML.Auth;
using COSXML.Common;
using COSXML.Model.Object;
using System;
using System.IO;
using up6.db.model;

namespace up6.db.store.cos
{
    public class CosTool
    {

        CosTool()
        {
        }

        public static CosXml createClient() {
            CosConfig cfg = new CosConfig();
            CosXmlConfig config = new CosXmlConfig.Builder()
              .SetRegion(cfg.region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
              .Build();

            long durationSecond = 600;          //每次请求签名有效时长，单位为秒
            var qc= new DefaultQCloudCredentialProvider(cfg.ak,cfg.sk, durationSecond);

            return new CosXmlServer(config, qc);
        }


        /// <summary>
        /// API:
        /// https://help.aliyun.com/document_detail/91093.html
        /// </summary>
        /// <param name="key">/123.txt</param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string putObject(string key, byte[] data)
        {
            CosConfig cfg = new CosConfig();
            try
            {
                MemoryStream ms = new MemoryStream(data);

                // 存储桶名称，此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer
                PutObjectRequest req = new PutObjectRequest(cfg.bucket, key, ms);
                // 发起上传
                PutObjectResult result = createClient().PutObject(req);
                Console.WriteLine(result.GetResultInfo());
                return result.GetResultInfo();
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
                System.Diagnostics.Debug.WriteLine("CosClientException: " + clientEx.Message);
                throw new IOException("cos put object error");
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                System.Diagnostics.Debug.WriteLine("CosServerException: " + serverEx.GetInfo());
                throw new IOException("cos put object error");
            }
        }

        public static string putObject(string key, string pathLoc)
        {
            return "";
        }


        /**
		 * API：
		 * 	https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/API/API_GetObject.html
		 * @param key 以左斜杠开始的资源路径。/guid/QQ.exe径
		 * @param blockOffset
		 * @param blockLen
		 * @return
		 */
        public static byte[] getObject(string key, long blockOffset, long blockLen)
        {
            return null;
        }

        /**
		 * API：
		 * 	https://cloud.tencent.com/document/product/436/47231
		 * @param key guid/QQ.exe，
		 * @return
		 */
        public static String CreateMultipartUpload(String key)
        {
            try
            {
                CosConfig cfg = new CosConfig();
                // 存储桶名称，此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer
                var request = new InitMultipartUploadRequest(cfg.bucket, key);
                var c = createClient();
                //执行请求
                InitMultipartUploadResult result = c.InitMultipartUpload(request);
                //请求成功
                var uploadId = result.initMultipartUpload.uploadId; //用于后续分块上传的 uploadId
                Console.WriteLine(result.GetResultInfo());
                return uploadId;
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
                System.Diagnostics.Debug.WriteLine("CosClientException: " + clientEx.Message);
                throw new IOException("cos CreateMultipartUpload error");
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                System.Diagnostics.Debug.WriteLine("CosServerException: " + serverEx.GetInfo());
                throw new IOException("cos CreateMultipartUpload error");
            }
        }

        /**
		 * API:
		 * 	https://cloud.tencent.com/document/product/436/47231
		 * @param key /guid/QQ.exe
		 * @param part 基于1
		 * @param uploadID
		 * @param data
		 */
        public static String UploadPart(String key, int part, String uploadID, byte[] data)
        {
            try
            {
                CosConfig cfg = new CosConfig();
                // 存储桶名称，此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer
                string srcPath = @"temp-source-file";//本地文件绝对路径
                UploadPartRequest request = new UploadPartRequest(cfg.bucket, key, part,
                  uploadID, srcPath, 0, -1);
                //设置进度回调
                request.SetCosProgressCallback(delegate (long completed, long total)
                {
                    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                });
                //执行请求
                UploadPartResult result = createClient().UploadPart(request);
                //请求成功
                //获取返回分块的eTag,用于后续CompleteMultiUploads
                var eTag = result.eTag;
                Console.WriteLine(result.GetResultInfo());
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
                return "";
        }

        /**
		 * 参数：pathSvr,minio_id(UploadId)
		 * API:
		 * 	https://help.aliyun.com/document_detail/91103.html
		 * POST /Key+?uploadId=UploadId HTTP/1.1
			Host: Bucket.s3.amazonaws.com
			<?xml version="1.0" encoding="UTF-8"?>
			<CompleteMultipartUpload xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
			   <Part>
				  <ChecksumCRC32>string</ChecksumCRC32>
				  <ChecksumCRC32C>string</ChecksumCRC32C>
				  <ChecksumSHA1>string</ChecksumSHA1>
				  <ChecksumSHA256>string</ChecksumSHA256>
				  <ETag>string</ETag>
				  <PartNumber>integer</PartNumber>
			   </Part>
			   ...
			</CompleteMultipartUpload>

		 * @param key
		 * @param id
		 */
        public static bool CompleteMultipartUpload(FileInf file)
        {
            return true;
        }
    }
}